import wx from 'weixin-js-sdk'
import {
  getWechatConfig
} from '@/api' 

async function wxConfig(url) {
  let config = {
    debug: false,// 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    appId: '', // 必填，公众号的唯一标识
    timestamp: '', // 必填，生成签名的时间戳
    nonceStr: '', // 必填，生成签名的随机串
    signature: '', // 必填，签名
    jsApiList: [
      // 'onMenuShareTimeline',
      // 'onMenuShareAppMessage',
      'hideMenuItems',
      'updateAppMessageShareData',
      'updateTimelineShareData'
    ], // 必填，需要使用的JS接口列表
    openTagList: ["wx-open-launch-weapp"]
  }

  let sendUrl = url.split("#")[0]
  getWechatConfig(sendUrl)
    .then(res => {
      config.appId = res.data.data.appId
      config.timestamp = res.data.data.timestamp
      config.nonceStr = res.data.data.nonceStr
      config.signature = res.data.data.signature
    })
    .then(() => wx.config(config))
}

async function wxShare({
  url,
  that,
  forbidding,
  weChatPrevented,
  ...shareData
}) {
  await wxConfig(url)
  wx.ready(function () {
    if (that.inviteFlag == 1) {
      wx.showOptionMenu();
    } else if (that.inviteFlag == 0 && that.isDistribution == 1) {
      wx.hideOptionMenu();
    }
    if (weChatPrevented) {
      wx.hideOptionMenu();
    } else {
      wx.showOptionMenu();
    }
    if (forbidding){
      wx.hideMenuItems({//'menuItem:copyUrl',
        menuList: ['menuItem:copyUrl','menuItem:openWithQQBrowser','menuItem:openWithSafari','menuItem:share:qq','menuItem:share:QZone'], // 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录3
        success: function (res) {
          console.log('已隐藏');
         },
         fail: function (res) {
          console.log(JSON.stringify(res));
         }
      });
    }
    console.log('shareData', shareData)
    wx.updateAppMessageShareData({
      title: shareData.title,
      imgUrl: shareData.imgUrl,
      link: shareData.link,
      desc: shareData.desc,
      success: function () {
        console.log('success')
        that.issuccess = false
        that.showPop = false
      }
    })
    wx.updateTimelineShareData({
      title: shareData.title,
      imgUrl: shareData.imgUrl,
      link: shareData.link,
      desc: shareData.desc,
      success: function () {
        console.log('success')
        that.issuccess = false
        that.showPop = false
      }
    })
  })
}

export {
  wxConfig,
  wxShare
}
